package com.example.controller.config.security.service;

import com.example.common.DozerUtils;
import com.example.model.ums.UmsAdmin;
import com.example.model.ums.UmsMenu;
import com.example.model.vo.UmsAdminVo;
import com.example.model.vo.UmsMenuVo;
import com.example.service.ums.UmsAdminService;
import com.example.service.ums.UmsMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户认证处理器
 */
@Component
public class CustomerUserDetailsService implements UserDetailsService {

    @Autowired
    private UmsAdminService service;

    @Autowired
    private UmsMenuService umsMenuService;

    @Autowired
    private BCryptPasswordEncoder cryptPasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(null == username || username.equals("")){
            throw new UsernameNotFoundException("用户名异常");
        }
        UmsAdmin admin = new UmsAdmin();
        admin.setUsername(username);
        System.out.println(cryptPasswordEncoder.encode("123456"));
        //根据用户名查找用户信息
        UmsAdmin umsAdminByParam = service.findUmsAdminByParam(admin);
        UmsAdminVo conversion = DozerUtils.conversion(umsAdminByParam, UmsAdminVo.class);
        //判断是否有用户
        if(null == umsAdminByParam){
            throw new UsernameNotFoundException("用户名或密码错误！");
        }
        UmsMenuVo vo = new UmsMenuVo();
        vo.setAdminId(conversion.getId());
        List<UmsMenu> umsMenuByAdminId = umsMenuService.findUmsMenuByAdminId(vo);

        //获取对应的权限编码
        List<String> collect = umsMenuByAdminId.stream().filter(Objects::nonNull)
                .map(item -> item.getMenuCode())
                .collect(Collectors.toList());
        //将权限编码转为数组
        String [] strings = collect.toArray(new String[collect.size()]);
        //设置权限列表
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(strings);
        //将权限列表设置给umsAdmin
        conversion.setAuthorities(authorityList);
        return conversion;
    }
}
